# coding=utf-8
from __future__ import division
import sys
from PyQt5.QtWidgets import QDialog, QTextBrowser, QLineEdit, QVBoxLayout, QApplication


class CaculatorDemo(QDialog):
    def __init__(self, parent=None):
        super(CaculatorDemo, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.lineedit.returnPressed.connect(self.update_ui)
        self.setWindowTitle("Calculate coding by lizhen")

    def update_ui(self):
        try:
            text = self.lineedit.text()
            self.browser.append("%s = <b>%s</b>" % (text, eval(text)))
            self.lineedit.clear()
        except Exception:
            self.browser.append("<font color=red>%s is invalid!</font>" % text)
            self.lineedit.clear()


def _test_caculator():
    """
    _test_caculator()
    """
    app = QApplication(sys.argv)
    cd = CaculatorDemo()
    cd.show()
    app.exec_()


if __name__ == '__main__':
    _test_caculator()
